<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>缓动动画</title>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
				box-sizing: border-box;
			}
			.box500 {
				position: absolute;
				top: 50px;
				left: 0;
				width: 150px;
				height: 150px;
				background-color: pink;
			}
			.box800 {
				position: absolute;
				top: 100px;
				left: 0;
				width: 200px;
				height: 200px;
				background-color: purple;
			}
		</style>
	</head>
	<body>
		<button class="btn500">移动500</button>
		<button class="btn800">移动800</button>
		<div class="box500"></div>
		<!--<div class="box800"></div>-->
		<script type="text/javascript">
			window.addEventListener('load',function() {
				var div500 =document.querySelector('.box500');
				var btn = document.querySelector('.btn500')
				//定义动画函数
				function animate(obj,target) {
					
					clearInterval(obj.timer)
					obj.timer = setInterval(function() {
						//定义每次移动的距离 (目标距离 - 盒子当前的距离) / 10
						var space = (target - obj.offsetLeft) / 10;
						//向右移动的时候 ，向上取整,向左移动间距向下取整
						space = space > 0 ? Math.ceil(space) : Math.floor(space);
						//判断盒子移动的距离是否大于目标距离
						if(obj.offsetLeft == target) {
							//清除定时器
							clearInterval(obj.timer)
						} else {
							//盒子每次移动1px
							obj.style.left = obj.offsetLeft + space + 'px'
						}
//obj.style.left = obj.offsetLeft + space + 'px'
					},15)
				}
				
				btn.addEventListener('click',function() {
					animate(div500,500)
				});
				
				var div800 = document.querySelector('.box800');
				var btnn = document.querySelector('.btn800');
				btnn.addEventListener('click',function() {
					animate(div500,800);
				})
				
				
				
			})
		</script>
	</body>
</html>
